<!--
切片上传控件，后端uploadFormFileSlice.action方法
只能单选，可以将进度显示到业务区域
handleHeadImgSuccess(fileList) {
//fileList是上传的文件列表，每次只有一个
      let $this = this;
      let files = JSON.parse($this.enquiryForm.file_ids || '[]');
      fileList.forEach(item => {
          files.push({
              sid: item.data.sid,
              name: item.data.original_file_name,
          });
      });
}
属性：uploadOption:{
            biz_type:'saleEnquiry',
            biz_table:'sale_enquiry',
            biz_sid:'',
            biz_field_tag:'attach',
            keep_file_name:'true'
        },
<SliceUpload ref="dialogMultipleUpload" class="uploadPicture" :on-success="handleHeadImgSuccess" :option="uploadOption"
             list-type="text">
    <template v-slot:default="slot">
        <el-button type="primary" :disabled="slot.ratio>0&&slot.ratio<100">上传{{slot.ratio>0?'（'+slot.ratio+' %）':''}}</el-button>
    </template>
</SliceUpload>
-->
<template>
    <div class="slice_upload_container">
        <el-upload ref="slice_upload" :action="uploadFileActionReplace" :before-upload="beforeUpload"
                   :headers="{ token: token,account_set_sid:account_set_sid }"
                   :on-change="handleChange"  :file-list="fileList" :multiple="option.multiple" :drag="option.drag"
                   :accept="option.accept" :limit="option.limit"
                   :on-remove="onRemove" :disabled="disabled">
            <slot :ratio="upload_ratio"/>
        </el-upload>
    </div>
</template>

<script>
    import fileApi from "@common/api/fileApi";

    export default {
        name: "SliceUpload",
        props: {
            onSuccess: Function,
            onRemove: Function,
            listType: String,
            fileList: {
                type: Array,
                default () {
                    return [];
                },
            },
            option:{
                type: Object,
                default () {
                    return {
                        biz_type:'',
                        biz_table:'',
                        biz_sid:'',
                        biz_field_tag:'',
                        multiple:false,
                        drag:true,
                        accept:"*",
                        limit:"99999",
                    };
                },
            },
            disabled: Boolean,
        },
        data () {
            return {
                upload_ratio:0,
                start_upload:false,
                fileInfoFromServer:{},
                fileApiUrl: fileApi.url,
                uploadedFile: [],
                respList: [],
                token: this.$store.state.accessToken.token,
                account_set_sid : this.$utils.getAccountSetSid(),
            };
        },
        watch: {
            fileList: {
                handler () {
                    this.respList = [];
                },
                deep: true,
                immediate: true,
            },
        },
        computed:{
            uploadFileActionReplace() {
                //由于启用了beforeUpload，并返回false，所以此方法的设置没用
                let path = this.fileApiUrl.uploadFile;
                return path;
            },
        },
        methods: {
            clear () {
                this.uploadedFile = [];
                this.respList = [];
                if (this.$refs['slice_upload']) {
                    this.$refs['slice_upload'].clearFiles()
                }
            },
            handleUploadSuccess (res, file, fileList) {
                console.log(res);
                this.uploadedFile.push(file);
                this.respList.push(res);
                typeof this.onSuccess === 'function' && this.onSuccess(this.respList);
                this.clear();
            },
            handleChange(file, fileList) {
                if (file.percentage<100){
                    this.start_upload = true;
                    this.upload_ratio = 0;
                    this.fileInfoFromServer={}
                    // this.uploadByPieces(file.raw)
                }
            },
            beforeUpload(file){
                this.uploadByPieces(file)
                return false
            },
            uploadByPieces(file){
                let $this = this;
                let pieceSize = 1
                const sliceSize = pieceSize * 1024 * 1024; // 1MB一片
                const sliceCount = Math.ceil(file.size / sliceSize); // 总片数
                const getSliceInfo = (file, sliceIndex, sliceSize) => {
                    let start = sliceIndex * sliceSize;
                    let end = Math.min(file.size, start + sliceSize);
                    let slice = file.slice(start, end);
                    return { start, end, slice };
                };
                // 针对每个文件进行slice处理
                const readSlice = () => {
                    // 针对单个文件进行slice上传
                    const { slice } = getSliceInfo(file, 0, sliceSize);
                    uploadSlice({ slice, sliceIndex: 0, sliceCount });
                };
                const uploadSlice = sliceInfo => {
                    let fetchForm = new FormData();
                    fetchForm.append("sliceIndex", sliceInfo.sliceIndex);
                    fetchForm.append("sliceSize", sliceSize);
                    fetchForm.append("sliceCount", sliceInfo.sliceCount);
                    fetchForm.append("file", sliceInfo.slice);
                    fetchForm.append("fileName", file.name);
                    fetchForm.append("totalLength", file.size);
                    if ($this.fileInfoFromServer && $this.fileInfoFromServer.sid){
                        fetchForm.append("fileInfoId", $this.fileInfoFromServer.sid);
                    }
                    if (this.$utils.isNotEmpty(this.option.biz_type)) {
                        fetchForm.append("biz_type", $this.option.biz_type);
                    }
                    if (this.$utils.isNotEmpty(this.option.biz_table)) {
                        fetchForm.append("associate_biz_table", $this.option.biz_table);
                    }
                    if (this.$utils.isNotEmpty(this.option.biz_sid)) {
                        fetchForm.append("associate_biz_sid", $this.option.biz_sid);
                    }
                    if (this.$utils.isNotEmpty(this.option.biz_field_tag)) {
                        fetchForm.append("associate_biz_field_tag", $this.option.biz_field_tag);
                    }
                    fetchForm.append("hideLoading", true);
                    fileApi.uploadFormFileSlice(fetchForm,res=>{
                        $this.fileInfoFromServer = res.data;
                        if (sliceInfo.sliceIndex < sliceInfo.sliceCount - 1) {
                            const { slice } = getSliceInfo(
                                file,
                                sliceInfo.sliceIndex + 1,
                                sliceSize
                            );
                            $this.upload_ratio = Number((sliceInfo.sliceIndex*100/sliceInfo.sliceCount).toFixed(0));
                            uploadSlice({
                                slice,
                                sliceIndex: sliceInfo.sliceIndex + 1,
                                sliceCount: sliceInfo.sliceCount
                            });
                        } else {
                            // 当总数大于等于分片个数的时候
                            if (sliceInfo.sliceIndex >= sliceInfo.sliceCount - 1) {
                                res.sliceIndex = sliceInfo.sliceIndex + 1;
                                res.sliceCount = sliceInfo.sliceCount;
                                $this.upload_ratio = 100;
                                window.setTimeout($this.clearRatio,5000);
                                $this.handleUploadSuccess(res,file,[]);
                            }
                        }
                    },res=>{
                        console.log(res.message);
                    },reason=>{
                        console.log(reason);
                    })
                };
                readSlice(); // 开始执行代码
            },
            clearRatio(){
                this.upload_ratio = 0
            },
        },
    }
</script>

<style scoped>
    .slice_upload_container {
        width: auto;
        height: auto;
    }

    .slice_upload_container .el-upload--text {
        border: none;
        width: auto;
        height: auto;
        border-radius: 0;
    }
</style>
